/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：MstCodeController   
 * 类描述：   编码控制层
 * 创建人：zhangl  
 * 创建时间：2016年10月13日 下午3:55:42   
 * 修改人：zhangl   
 * 修改时间：2016年10月13日 下午3:55:42   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.FolPara;
import com.lst.model.MstButton;
import com.lst.model.MstCode;
import com.lst.model.MstMenu;
import com.lst.model.MstUser;
import com.lst.service.MstButtonService;
import com.lst.service.MstCodeService;
import com.lst.service.MstMenuService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: MstCodeController
 * @Description:编码控制层
 * @author zhangl
 * @date 2016年10月13日 下午3:55:42
 *
 */
@Controller
@RequestMapping("mstCodeController")
public class MstCodeController extends BaseController {

	@Autowired
	private MstCodeService mstCodeService;

	@Autowired
	private MstButtonService mstButtonService;
	
	@Autowired
	private MstMenuService mstMenuService;

	/**
	 * 
	 * @Title: list
	 * @Description: 页面加载
	 * @param @param menuId
	 * @param @param parentId
	 * @param @param type
	 * @param @param page
	 * @param @param rows
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param codeName
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(
			@RequestParam(required = true) Integer menuId,
			@RequestParam(required = false,defaultValue = "") String parentId,
			@RequestParam(required = false,defaultValue = "") String type,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) int page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) int rows,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String codeName) throws MyException {
		Date startDate = new Date();
		logger.info("list begin: " + startDate);

		FolPara folPara = new FolPara();
		folPara.setMenuId(menuId);
		folPara.setParentId(parentId);
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setCodeName(codeName);
		folPara.setType(type);

		MstUser mstUser = this.getMySession().getMstUser();

		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId, mstUser, mstButtonService);
		MstMenu mstMenu = mstMenuService.selectByPrimaryKey(Integer.valueOf(menuId));
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("btns", btns);
		mv.addObject("folPara",folPara);
		mv.addObject("menuId",menuId);
		mv.addObject("mstMenu",mstMenu);

		if(StringUtils.isEmpty(type)){
			mv.setViewName(CommonEnum.FORWARD_VIEW_MAIN_CODE + "code_list");
		} else {
			mv.setViewName(CommonEnum.FORWARD_VIEW_MAIN_CODE + "quen_list");
		}

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("list end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: queryList
	 * @Description: 查询结果集
	 * @param @param parentId
	 * @param @param type
	 * @param @param page
	 * @param @param rows
	 * @param @param sort
	 * @param @param order
	 * @param @param codeName
	 * @param @return    设定文件
	 * @return Object    返回类型
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(
			@RequestParam(required = false,defaultValue = "")String parentId,
			@RequestParam(required = false,defaultValue = "")String type,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer rows,
			@RequestParam(required = false,defaultValue = "")String sort,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEM_ORDER_DESC)String order,
			@RequestParam(required = false,defaultValue = "")String codeName) {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("isDeleted", 0);
		//reqMap.put("enabled", 1);

		if(StringUtils.isEmpty(sort)){
			reqMap.put("orderByClause","c.createdate desc");
		} else{
			reqMap.put("orderByClause",sort + " " + order);
		}

		if(!StringUtils.isBlank(codeName)){
			reqMap.put("_codeName", codeName.trim());
		}

		if(!StringUtils.isBlank(parentId)){
			reqMap.put("parentId", parentId);
		}

		if(!StringUtils.isBlank(type)){
			reqMap.put("type", type);
		}

		PageBounds pageBounds = new PageBounds(page, rows);

		List<MstCode> list = null ; 
		if(!StringUtils.isBlank(parentId)){
			list = mstCodeService.queryByList(reqMap, pageBounds);
		} else {
			//获取所有问卷
			list = mstCodeService.queryByList(reqMap, pageBounds);
			//后去所有答案
			PageBounds _pageBounds = new PageBounds();
			List<MstCode> _list = null;
			for(MstCode mstCode : list){
				reqMap.put("parentId", mstCode.getId());
				_list = mstCodeService.queryByList(reqMap, _pageBounds);
				mstCode.setCodes(_list);
			}
			
		}

		PageList<MstCode> pageList = (PageList<MstCode>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> easyUIPages = new HashMap<String, Object>();
		easyUIPages.put("total", paginator.getTotalCount());
		easyUIPages.put("rows", list);

		logger.info("queryList end run(s): " + DateUtil.calLastedTime(startDate));

		return easyUIPages;
	}

	/**
	 * 
	 * @Title: edit
	 * @Description:编辑
	 * @param @param id
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param type
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false) String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String type) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView();

		if (!StringUtils.isBlank(id)) {
			MstCode mstCode = mstCodeService.selectByPrimaryKey(Integer.valueOf(id));
			mv.addObject("mstCode",mstCode);
		}

		mv.setViewName(CommonEnum.FORWARD_VIEW_MAIN_CODE + "code_edit");

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: quenEdit
	 * @Description:编辑答卷
	 * @param @param id
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param type
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/quenEdit")
	public ModelAndView quenEdit(
			@RequestParam(required = false) String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String type) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView();

		if (!StringUtils.isBlank(id)) {
			MstCode mstCode = mstCodeService.selectByPrimaryKey(Integer.valueOf(id));
			mv.addObject("mstCode",mstCode);
		}

		Map<String, Object> codeMap = new HashMap<String, Object>();
		codeMap.put("isDeleted", 0);
		codeMap.put("enabled", 1);
		codeMap.put("parentId", id);

		codeMap.put("orderByClause","c.id desc");

		PageBounds pageBounds = new PageBounds();

		List<MstCode> mstCodes = mstCodeService.queryByList(codeMap, pageBounds);

		mv.setViewName(CommonEnum.FORWARD_VIEW_MAIN_CODE + "quen_edit");

		mv.addObject("mstCodes", mstCodes);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * @throws MyException 
	 * 
	 * @Title: save
	 * @Description:save
	 * @param @param request
	 * @param @param response
	 * @param @param mstrole
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public String save(MstCode mstcode,FolPara folPara,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);

		MstUser mstUser = this.getMySession().getMstUser();

		if(!StringUtils.isEmpty(folPara.getParentId())){
			mstcode.setParentid(Integer.valueOf(folPara.getParentId()));
		}

		if (mstcode.getId() != null) {
			mstcode.setUpdatedate(startDate);
			mstcode.setUpdateuser(mstUser.getId());

			mstCodeService.updateByPrimaryKeySelective(mstcode);
		} else {
			mstcode.setIsdeleted(false);
			mstcode.setCreatedate(startDate);
			mstcode.setCreateuser(mstUser.getId());

			mstCodeService.insert(mstcode);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&rows=" + folPara.getRows());
		sb.append("&index_exp=" + index_exp);
		sb.append("&index_che=" + index_che);
		sb.append("&codeName=" + folPara.getCodeName());
		sb.append("&parentId=" + folPara.getParentId());
		sb.append("&type=" + folPara.getType());
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s):" + DateUtil.calLastedTime(startDate));

		String result = "redirect:list" + sb.toString();

		return result;
	}

	/**
	 * 
	 * @Title: saveWithList
	 * @Description:数据更新
	 * @param @param mstCodes
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return String    返回类型
	 */
	@RequestMapping(value = "/saveWithList")
	@ResponseBody
	public boolean saveWithList(@RequestBody List<MstCode> mstCodes) throws MyException {
		Date startDate = new Date();
		logger.info("saveWithList begin: " + startDate);

		MstUser mstUser = this.getMySession().getMstUser();

		boolean flag = false;

		try {

			if(mstCodes!= null && !mstCodes.isEmpty()){

				Map<String, Object> delMap = new HashMap<String,Object>();
				delMap.put("updateUser", mstUser.getId());
				delMap.put("parentId", mstCodes.get(0).getParentid());

				for(MstCode mstCode : mstCodes){
					mstCode.setCreateuser(mstUser.getId());
					mstCode.setIsdeleted(false);
					mstCode.setCreatedate(startDate);
				}

				mstCodeService.saveWithList(delMap, mstCodes);

				flag = true;
			}

		} catch (Exception e) {
			logger.error("saveWithList error: " ,e);
		}

		logger.info("save end run(s):" + DateUtil.calLastedTime(startDate));

		return flag;
	}

	/**
	 * 
	 * @Title: queryListByParentId
	 * @Description: 根据parentId查询数据集
	 * @param @param parentId
	 * @param @return    设定文件
	 * @return List<MstCode>    返回类型
	 */
	@RequestMapping("queryListByParentId")
	@ResponseBody
	public List<MstCode> queryListByParentId(@RequestParam(required = true)Integer parentId){
		Date startDate = new Date();
		logger.info("queryListByParentId begin: " + startDate);

		List<MstCode> list = mstCodeService.queryListByParentId(parentId);

		logger.info("queryListByParentId end run(s): " + DateUtil.calLastedTime(startDate));

		return list;
	}

	/**
	 * 
	 * @Title: queryListWithParents
	 * @Description: 获取父级编码集
	 * @param @return    设定文件
	 * @return List<MstCode>    返回类型
	 */
	@RequestMapping("queryListWithParents")
	@ResponseBody
	public List<MstCode> queryListWithParents(){
		Date startDate = new Date();
		logger.info("queryListWithParents begin: " + startDate);

		Map<String, Object> decMap = new HashMap<String,Object>();
		decMap.put("isdeleted", 0);
		decMap.put("enabled", 1);
		decMap.put("parentId", -1);
		decMap.put("orderByClause","c.id asc");

		List<MstCode> list = mstCodeService.queryByList(decMap, new PageBounds());

		logger.info("queryListWithParents end runs(s): " + DateUtil.calLastedTime(startDate));

		return list;
	}

	/**
	 * 
	 * @Title: initCodeByParentId
	 * @Description: 根据parentId初始化code编码
	 * @param @param parentId 上级id
	 * @param @param ids      默认选择的ids集
	 * @param @return    设定文件
	 * @return List<MstCode>    返回类型
	 */
	@RequestMapping(value = "initCodeByParentId" , method = RequestMethod.GET)
	@ResponseBody
	public List<MstCode> initCodeByParentId(
			@RequestParam(required = true)Integer parentId,
			@RequestParam(required = false,defaultValue = "")String ids){
		Date startDate = new Date();
		logger.info("initCodeByParentId begin: " + startDate);

		List<MstCode> list = mstCodeService.queryListByParentId(parentId);

		if(!StringUtils.isBlank(ids)){
			List<MstCode> _list = mstCodeService.queryListByIds(ids);
			for(MstCode code : list){
				for(MstCode _code : _list){
					if(code.getId().equals(_code.getId())){
						code.setFlag(true);
						break;
					}
				}
			}
		}

		logger.info("initCodeByParentId end run(s): " + DateUtil.calLastedTime(startDate));

		return list;
	}

	/**
	 * 
	 * @Title: delList
	 * @Description: 批量删除功能
	 * @param @param ids
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return boolean    返回类型
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(
			@RequestParam(required = true) String ids) throws MyException {
		Date startDate = new Date();
		logger.info("delList begin: " + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("ids", ids);
		reqMap.put("updateUser", mstUser.getId());

		try {
			mstCodeService.delList(reqMap);
			flag = true;
		} catch (Exception e) {
			logger.error("delList error: " ,e);
		}

		logger.info("delList end run(s): " + DateUtil.calLastedTime(startDate));

		return flag;
	}

}
